package com.hbplat.shardingsphere.util;

import java.text.DecimalFormat;

public class NumberUtil {

    /**
     * 转为int
     * @param o
     * @return
     */
    public static int safeToNumber(Object o){
        int r = 0;
        if (o != null) {
            try {
                r = new Integer(String.valueOf(o));
            } catch (Exception var4) {
            	var4.printStackTrace();
            }
        }

        return r;
    }

    /**
     * 转double
     * @param o
     * @return
     */
    public static Double safeToDouble(Object o){
        double d = 0.0;
        if(o != null){
            try{
                d = new Double(StringUtil.valueOfString(o));
            }catch (Exception e){
            }
        }
        return d;
    }


    /**
     * 转double
     * @param o
     * @return
     */
    public static Double safeToDouble(Object o, double defaultNum){
        double d = 0.0;
        if(o != null){
            try{
                d = new Double(StringUtil.valueOfString(o));
            }catch (Exception e){

            }
            if(d == 0.0){
                return defaultNum;
            }
        }
        return d;
    }


    /**
     * 转数字 如为空则为默认值
     * @param o
     * @param defaultNum
     * @return
     */
    public static int safeToNumber(Object o, int defaultNum){
        int r = 0;
        if (o != null) {
            try {
                r = new Integer(String.valueOf(o));
            } catch (Exception var4) {
            }
        }
        if(r  == 0){
            return defaultNum;
        }
        return r;
    }

    /**
     * 转数字 如为空则为默认值
     * @param o
     * @param defaultNum
     * @return
     */
    public static long safeToLong(Object o, long defaultNum){
        long r = 0;
        if (o != null) {
            try {
                r = new Long(String.valueOf(o));
            } catch (Exception var4) {
            }
        }
        if(r  == 0){
            return defaultNum;
        }
        return r;
    }
    
    
    

    /**
     * 转数字 如为空则为默认值
     * @param o
     * @return
     */
    public static long safeToLong(Object o){
        long r = 0;
        if (o != null) {
            try {
                r = new Long(String.valueOf(o));
            } catch (Exception var4) {
            }
        }
        if(r  == 0){
            return r;
        }
        return r;
    }
    
    /**
     * double 保留两位小数
     * @param x
     * @return
     */
    public static double parseDoubleFormart(double x) {
    	DecimalFormat df=new DecimalFormat(".##");
    	String s= df.format(x);
    	return new Double(s);
    }
    /**
     * double 保留两位小数
     * @param x
     * @return
     */
    public static String parseDoubleFormartStr(double x) {
    	DecimalFormat df=new DecimalFormat("#####.##");
    	String s= df.format(x);
    	return  s;
    }
    public static void  main(String[] args) {
    	System.out.println(NumberUtil.parseDoubleFormart(0.314444));
    }
}
